// pages/home/home.js
const app = getApp()
var moveFlag = true;// 判断执行滑动事件
var startX, endX;  //接触开始和结束x坐标
var moveFlag = true;//确保移动方向为首次

const db = wx.cloud.database()
const _ = db.command
const publishDB=db.collection('publishData') //公告数据库
const reportDB=db.collection('reportData')
const pageSize=10

var windowHeight = 0  //可用视图的高度
var totalPage = 0   //总页数

Page({
  page: 1,//页数
  postflg: true,//是否可以加载列表，用户误触控制

  /**
   * 页面的初始数据
   */
  data: {
    currentClick: 1,      //栏目 :筛选条件之一
    academyArray: [],     //学院筛选条件子二
    labelArray: [],       //标签筛选条件子三
    noListData: "",       //返回无数据
    loadMore: false,      //"上拉加载"的变量，默认false，隐藏  
    loadAll: false,       //“没有数据”的变量，默认false，隐藏
    // windowHeight: 0,      //可用视图的高度
    scrollViewHeight: 0,  // scroll-view的高度
    scrollTop:0,          //切换栏目时是滚动条回到顶部
    // totalPage: 0,         //总页数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    //获取系统参数
    wx.getSystemInfo({
      success: function (res) {
        console.log("res", res)
        // that.setData({
        //   windowHeight: res.windowHeight
        // })
        windowHeight =  res.windowHeight
        // console.log("windowHeight",that.data.windowHeight)
        let query = wx.createSelectorQuery().in(that);
        query.select('.nav_view').boundingClientRect();
        query.exec((res) => {
          let topHeight = res[0].height
          let height = windowHeight - topHeight
          // console.log("topHeight", topHeight)
          // console.log("height", height)
          that.setData({
            scrollViewHeight: height
          })
          // console.log("scrollViewHeight",that.data.scrollViewHeight)
        })
        that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)
      },
    })
  },

  onShow: function () {
      let that = this
      that.onLoad()
  },

  //导航栏点击事件
  clickNavT: function () {//寻物栏
    var that = this
    that.page = 1
    that.setData({
      currentClick: 1,  //当前导航栏
      academyArray: [], //学院筛选条件子二
      labelArray: [],   //标签筛选条件子三
      list: [],         //清空数组
    })
    //获取栏目下所有公告，不含有其他筛选条件
    that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)
  },
  clickNavM: function () {//找人栏
    var that = this
    that.page = 1
    that.setData({
      currentClick: 2,
      academyArray: [],
      labelArray: [],
      list: [],
    })
    that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)
  },
  clickNavS: function () {//表白栏
    var that = this
    that.page = 1
    that.setData({
      currentClick: 3,
      academyArray: [],
      labelArray: [],
      list: [],
    })
    that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)
  },
  //屏幕滑动事件
  //触摸开始
  touchStart: function (e) {
    console.log("触摸开始")
    startX = e.touches[0].pageX;
    moveFlag = true;
  },

  // 触摸移动事件
  touchMove: function (e) {
    console.log("移动")
    var that = this
    endX = e.touches[0].pageX;
    if (moveFlag) {
      if (endX - startX > 100) {
        console.log("左滑");
        that.moveright();
        moveFlag = false;
      }
      if (startX - endX > 100) {
        console.log("右滑");
        that.moveleft();
        moveFlag = false;
      }
    }
  },

  touchEnd: function (e) {
    console.log("触摸结束")
    moveFlag = true; // 回复滑动事件 
  },

  moveleft() {
    var that = this;
    let currentPage = that.data.currentClick
    if (currentPage >= 3) {
      wx.showToast({
        title: '滑动到最右了哦~',
        icon: "none"
      })
    } else {
      currentPage += 1
      that.page = 1
      that.setData({
        currentClick: currentPage,
        academyArray: [],
        labelArray: [],
        list: [],
      });
      that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)//滑动栏目刷新数据
    }
  },
  moveright() {
    var that = this;
    let currentPage = that.data.currentClick
    if (currentPage <= 1) {
      wx.showToast({
        title: '滑动到最左了哦~',
        icon: "none"
      })
    } else {
      currentPage -= 1
      that.page = 1
      that.setData({
        currentClick: currentPage,
        academyArray: [],
        labelArray: [],
        list: [],
      });
      that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)//滑动栏目刷新数据
    }
  },

  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    var that = this
    that.page = 1
    that.setData({
      list: [],
    })
    wx.showNavigationBarLoading()//显示导航条加载动画
    that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)
    setTimeout(() => {
      wx.hideNavigationBarLoading()//隐藏导航条加载动画
      wx.stopPullDownRefresh()
    }, 2000);
  },

  //点击筛选按钮  页面跳转并传递当前栏目序号
  filterTag: function () {
    let column = this.data.currentClick
    wx.navigateTo({
      url: './filter/filter?col=' + column,
    })
  },

  //筛选条件改变后调用该方法
  changeData: function () {
    console.log("filter之后调用")
    var that = this;
    that.page = 1
    that.setData({
      list: [],
    })
    that.onLoad();
  },

  getPublishbyCondition: function (page, col, academyArray, labelArray) {
    var that = this
    wx.showLoading({
      title: '加载中',
    })

    that.setData({
      noListData: ""
    })
    // console.log("调用云函数getListData")
    wx.cloud.callFunction({
      
      name: 'getListData',// 要调用的云函数名称
      data: {             // 传递给云函数的event参数
        _col: col,
        _academyArray: academyArray,
        _labelArray: labelArray,
        _pageSize: pageSize,//每页item数量
        _page: page,        //第几页
      }
    }).then(res => {
      console.log("返回res", res)
      if (res.result && res.result.totalPage > 0) {//筛选之后有数据
        // let _totalPage = res.result.totalPage
        // console.log("总页数totalPage:", _totalPage)
        let index = that.page - 1
        totalPage = res.result.totalPage
        that.setData({
          // totalPage: _totalPage,
          // list: that.data.list.concat(res.result.data.list),
          ['list[' + index + ']']: res.result.data.list,//二维数组，防止setData数据量过大
        })
        console.log("that.data.list", that.data.list)
        that.postflg = true   //可用继续触发触底函数
      } else {//筛选之后没有数据
        that.setData({
          list:[],
          noListData: "暂时没有你想要筛选的内容!"
        })
        // console.log("noListData", that.data.noListData)
      }

      wx.hideLoading()

    }).catch(err => {
      console.error(err)
    })
    console.log("云函数getListData调用完成")
  },

  /*触底获取更多数据
    如果当前页数>=总页数，没有更多数据
        当前页数<总页数,还有数据
  */
  reachBottom: function () {
    var that = this
    // console.log("当前页page：", that.page)
    if (that.postflg) {
      that.postflg = false;//请求完成前不再更改页码请求接口
      if (that.page >= totalPage) {
        wx.showToast({
          title: '亲,没有更多数据了',
          icon: 'none',
          duration: 2000
        })
      } else {
        that.page++;//页数加一
        that.getPublishbyCondition(that.page, that.data.currentClick, that.data.academyArray, that.data.labelArray)
      }
    }
  },

  //点击图片放大预览
  previewImage: function (e) {
    // // console.log("e",e)
    // var url = e.currentTarget.dataset.url
    // var urls = e.currentTarget.dataset.urls
    // wx.previewImage({
    //   current: url, // 当前显示图片的http链接
    //   urls: urls // 需要预览的图片http链接列表
    // })
    app.previewImage(e)
  },

  //跳转详情页
  clickNavDetail: function (e) {
    console.log("点击产生的数据", e)
    //将点击的item的数据传递给详情页，免得详情页再访问数据库，item的数据量也不是很多
    let item = JSON.stringify(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: './publishDetail/publishDetail?item=' + item
    })
  },

  //点击更多按钮
  clickMore:function(e){
    console.log("公告ID",e)
    let that = this
    let publishid = e.currentTarget.id
    wx.showActionSheet({
      itemList: ['举报'],
      success (res) {
        console.log(res.tapIndex)
        if(0==res.tapIndex){
          if (app.globalData.userOpenid==null){//未登录
            console.log("请先登录")
            wx.showToast({
              title: '请先登录',
              icon: "none",
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.switchTab({
                    url: '/pages/mine/mine',
                  })
                }, 2000);
              }
            })  
          }else{
          reportDB.where(_.and({
            publishID: publishid 
          },{
            Reporter:app.globalData.userOpenid
          })).count().then(res => {
            console.log(res.total)
            if(res.total==0){
              wx.navigateTo({
                url: '../home/report/report?publishID='+publishid,
              })
            }else{
              wx.showToast({
                title: '你已经举报过了哦',
                icon:"none"
              })
            }
          })
        }
        }
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
})